
//
//  CardAddController.m
//  EasyCar
//
//  Created by nsm on 2018/1/9.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "CardAddController.h"
#import "BankListController.h"

@interface CardAddController () <UITextFieldDelegate> {
    NSMButton   *_submitBtn;
    UITextField *_cardField;
}
@end

@implementation CardAddController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createContentView];
}

- (void)createContentView {
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.myTop = 15;
    layout.myHorzMargin = 0;
    [self.view addSubview:layout];
    
    MyLinearLayout *itemLayout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    itemLayout.myHorzMargin = 0;
    itemLayout.padding = UIEdgeInsetsMake(0, 15, 0, 15);
    itemLayout.backgroundColor = [UIColor whiteColor];
    [layout addSubview:itemLayout];
    
    NSArray *items = @[@{@"title": @"卡号",
                         @"placeholder": @"银行卡号",
                         @"id": @"card",
                         @"keyboard": @(UIKeyboardTypeNumberPad)},
                       @{@"title": @"银行",
                         @"placeholder": @"选择发卡银行",
                         @"id": @"bank_code",
                         @"keyboard": @(UIKeyboardTypeNumberPad)},
                       @{@"title": @"姓名",
                         @"id": @"name",
                         @"keyboard": @(UIKeyboardTypeDefault),
                         @"placeholder": @"持卡人姓名"}];
    @nsm_weak(self)
    for (int i=0; i<items.count; i++) {
        NSDictionary *item = items[i];
        UILabel *leftLabel = [self labelForLeft:item[@"title"]];
        UITextField *field = [UITextField new];
        field.tag = i;
        field.mark = self.className;
        field.identifierEx = item[@"id"];
        field.myHorzMargin = 0;
        field.myHeight = 54;
        field.font = CustomFont(15);
        field.tintColor = THEME_COLOR;
        field.textColor = [UIColor darkGrayColor];
        field.placeholder = item[@"placeholder"];
        field.keyboardType = [item[@"keyboard"] integerValue];
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        [itemLayout addSubview:field];
        
        field.leftView = leftLabel;
        field.leftViewMode = UITextFieldViewModeAlways;
        
        [field addBlockForControlEvents:UIControlEventEditingChanged block:^(UITextField *sender) {
            @nsm_strong(self)
            self.mutableDic[sender.identifierEx] = SafeString(sender.text);
            if (sender.text.length)
                SetBit(self.maskCode, sender.tag);
            else
                ClearBit(self.maskCode, sender.tag);
            
            [self check];
        }];
        
        if (i == 0) {
            field.delegate = self;
            _cardField = field;
        }
        
        if (i==1) {
            field.delegate = self;
            field.rightView = ArrowImageView(SUB_TEXT_COLOR, 1);
            field.rightViewMode = UITextFieldViewModeAlways;
        }

        if (i<items.count-1) {
            UIView *line = [UIView new];
            line.backgroundColor = GROUP_TABLECOLOR;
            line.myHorzMargin = 0;
            line.myHeight = [MyDimeScale roundNumber:0.5];
            [itemLayout addSubview:line];
        }
    }
    
    _submitBtn = [NSMButton buttonWithTitle:@"确定" target:self action:@selector(submit)];
    _submitBtn.myHorzMargin = 20;
    _submitBtn.myTop = 44;
    [layout addSubview:_submitBtn];
}

- (UILabel *)labelForLeft:(NSString *)text {
    UILabel *label = [UILabel new];
    label.size = CGSizeMake(50, 44);
    label.font = CustomFont(16);
    label.textColor = [UIColor blackColor];
    label.text = text;
    return label;
}

#pragma mark - textfielddelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (![textField.identifierEx isEqual:@"bank_code"]) return YES;
    
    BankListController *vc = [BankListController new];
    vc.title = @"银行";
    @nsm_weak(self)
    vc.didSelected = ^(id obj) {
        @nsm_strong(self)
        textField.text = obj[@"bank_name"];
        self.mutableDic[textField.identifierEx] = SafeString(obj[@"bank_code"]);
        SetBit(self.maskCode, textField.tag);
    };
    [self.navigationController pushViewController:vc animated:YES];
    
    return NO;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.identifierEx isEqual:@"card"]) {
        // 4位分隔银行卡卡号
        NSString *text = textField.text;
        
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
            [self check];
            return NO;
        }
        
        text = [text stringByReplacingCharactersInRange:range withString:string];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        NSString *newString = @"";
        while (text.length > 0) {
            NSString *subString = [text substringToIndex:MIN(text.length, 4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length == 4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length, 4)];
        }
        
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        
        if ([newString stringByReplacingOccurrencesOfString:@" " withString:@""].length >= 21) {
            [self check];
            return NO;
        }
        
        [textField setText:newString];
        
        [self check];
        return NO;
    }
    return YES;
}

- (void)check {
    NSString *text = [_cardField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.mutableDic[_cardField.identifierEx] = SafeString(text);
    if (text.length)
        SetBit(self.maskCode, _cardField.tag);
    else
        ClearBit(self.maskCode, _cardField.tag);
    // 0111
    BOOL enable = ((self.maskCode & 0x7) == 0x7);
    _submitBtn.selected = enable;
    _submitBtn.enabled = enable;
}

- (void)submit {
    [_networker POST:@"mine/addBankcard.html" parameters:self.mutableDic success:^(id responseObject) {
        !self.didAddCardSuccess?:self.didAddCardSuccess();
        [self.navigationController popViewControllerAnimated:YES];
    } empty:nil failure:nil];
}

@end
